/**
 * Statistics Dashboard UI
 * Provides a modern interface for viewing proxy statistics
 */

/**
 * Get the complete HTML for the statistics dashboard page
 * @returns {string} Complete HTML page with embedded styles and scripts
 */
export function getStatsDashboardHTML() {
  return `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Statistics Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header-left h1 {
            color: #333;
            font-size: 2rem;
            margin-bottom: 10px;
        }
        
        .header-left p {
            color: #666;
            font-size: 1rem;
        }
        
        .refresh-btn {
            padding: 12px 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .refresh-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-card .icon {
            width: 40px;
            height: 40px;
            margin: 0 auto 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .stat-card .icon svg {
            width: 20px;
            height: 20px;
            stroke: white;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: bold;
            color: #333;
            margin: 10px 0 5px;
        }
        
        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }
        
        .charts-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }
        
        .chart-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .chart-card h2 {
            color: #333;
            font-size: 1.3rem;
            margin-bottom: 20px;
        }
        
        .errors-section {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .errors-section h2 {
            color: #333;
            font-size: 1.3rem;
            margin-bottom: 20px;
        }
        
        .errors-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .errors-table th {
            background: #f5f5f5;
            padding: 12px;
            text-align: left;
            color: #666;
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .errors-table td {
            padding: 12px;
            border-bottom: 1px solid #eee;
            color: #333;
            font-size: 0.9rem;
        }
        
        .error-status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        
        .status-400 { background: #fff3cd; color: #856404; }
        .status-401 { background: #f8d7da; color: #721c24; }
        .status-403 { background: #f8d7da; color: #721c24; }
        .status-404 { background: #cce5ff; color: #004085; }
        .status-409 { background: #fff3cd; color: #856404; }
        .status-500 { background: #f8d7da; color: #721c24; }
        
        .export-section {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }
        
        .export-btn {
            padding: 10px 20px;
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .export-btn:hover {
            background: #667eea;
            color: white;
        }
        
        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                text-align: center;
                gap: 20px;
            }
            
            .charts-section {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-left">
                <h1>📊 Statistics Dashboard</h1>
                <p id="lastUpdated">Loading statistics...</p>
            </div>
            <button class="refresh-btn" onclick="refreshStats()">🔄 Refresh</button>
        </div>
        
        <div class="stats-grid">
            <div class="stat-card">
                <div class="icon">
                    <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path>
                    </svg>
                </div>
                <div class="stat-value" id="totalRequests">0</div>
                <div class="stat-label">Total Requests</div>
            </div>
            
            <div class="stat-card">
                <div class="icon">
                    <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                </div>
                <div class="stat-value" id="successRate">0%</div>
                <div class="stat-label">Success Rate</div>
            </div>
            
            <div class="stat-card">
                <div class="icon">
                    <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                </div>
                <div class="stat-value" id="avgDuration">0ms</div>
                <div class="stat-label">Avg Response Time</div>
            </div>
            
            <div class="stat-card">
                <div class="icon">
                    <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                </div>
                <div class="stat-value" id="totalErrors">0</div>
                <div class="stat-label">Total Errors</div>
            </div>
            
            <div class="stat-card">
                <div class="icon">
                    <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z"></path>
                    </svg>
                </div>
                <div class="stat-value" id="totalSize">0 MB</div>
                <div class="stat-label">Total Data</div>
            </div>
            
            <div class="stat-card">
                <div class="icon">
                    <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                    </svg>
                </div>
                <div class="stat-value" id="activeEndpoints">0</div>
                <div class="stat-label">Active Endpoints</div>
            </div>
        </div>
        
        <div class="charts-section">
            <div class="chart-card">
                <h2>📈 Request Timeline</h2>
                <canvas id="timelineChart"></canvas>
            </div>
            
            <div class="chart-card">
                <h2>🎯 Top Endpoints</h2>
                <canvas id="endpointChart"></canvas>
            </div>
        </div>
        
        <div class="errors-section">
            <h2>⚠️ Recent Errors</h2>
            <table class="errors-table">
                <thead>
                    <tr>
                        <th>Time</th>
                        <th>Endpoint</th>
                        <th>Error</th>
                        <th>Status Code</th>
                    </tr>
                </thead>
                <tbody id="errorsTableBody">
                    <tr>
                        <td colspan="4" style="text-align: center; color: #999;">Loading errors...</td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <div class="export-section">
            <button class="export-btn" onclick="exportStats('json')">📥 Export JSON</button>
            <button class="export-btn" onclick="exportStats('csv')">📊 Export CSV</button>
        </div>
    </div>

    <script>
        let statsData = {};
        let timelineChart = null;
        let endpointChart = null;

        async function loadStats() {
            try {
                const response = await fetch('/api/monitor/stats');
                if (!response.ok) throw new Error('Failed to fetch stats');
                statsData = await response.json();
                updateDashboard();
            } catch (error) {
                console.error('Error loading stats:', error);
            }
        }

        function updateDashboard() {
            // Update header
            const lastUpdated = statsData.lastUpdated ? new Date(statsData.lastUpdated) : new Date();
            document.getElementById('lastUpdated').textContent = 'Last updated: ' + lastUpdated.toLocaleString();
            
            // Calculate totals
            const allData = Object.values(statsData.allTime || {});
            const totalRequests = allData.reduce((sum, ip) => sum + (ip.totalRequests || 0), 0);
            const successfulRequests = allData.reduce((sum, ip) => sum + (ip.successfulRequests || 0), 0);
            const failedRequests = allData.reduce((sum, ip) => sum + (ip.failedRequests || 0), 0);
            const totalDuration = allData.reduce((sum, ip) => sum + (ip.totalDuration || 0), 0);
            const totalSize = allData.reduce((sum, ip) => sum + ((ip.totalRequestSize || 0) + (ip.totalResponseSize || 0)), 0);
            const successRate = totalRequests > 0 ? (successfulRequests / totalRequests) * 100 : 100;
            const avgDuration = totalRequests > 0 ? totalDuration / totalRequests : 0;
            
            // Count unique endpoints
            const endpoints = new Set();
            allData.forEach(ipData => {
                Object.keys(ipData.endpoints || {}).forEach(endpoint => endpoints.add(endpoint));
            });
            
            // Update stats cards
            document.getElementById('totalRequests').textContent = totalRequests.toLocaleString();
            document.getElementById('successRate').textContent = successRate.toFixed(2) + '%';
            document.getElementById('avgDuration').textContent = Math.round(avgDuration) + 'ms';
            document.getElementById('totalErrors').textContent = failedRequests.toLocaleString();
            document.getElementById('totalSize').textContent = (totalSize / (1024 * 1024)).toFixed(2) + ' MB';
            document.getElementById('activeEndpoints').textContent = endpoints.size;
            
            // Update charts
            updateTimelineChart();
            updateEndpointChart();
            
            // Update errors table
            updateErrorsTable();
        }

        function updateTimelineChart() {
            const ctx = document.getElementById('timelineChart').getContext('2d');
            
            // Prepare data
            const intervals = Object.entries(statsData.intervals || {})
                .sort(([a], [b]) => new Date(a) - new Date(b))
                .slice(-20);
            
            const labels = intervals.map(([time]) => {
                const date = new Date(time);
                return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
            });
            
            const requests = intervals.map(([, data]) => 
                Object.values(data).reduce((sum, ip) => sum + (ip.requests || 0), 0)
            );
            
            const errors = intervals.map(([, data]) => 
                Object.values(data).reduce((sum, ip) => sum + (ip.failed || 0), 0)
            );
            
            if (timelineChart) {
                timelineChart.destroy();
            }
            
            timelineChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Requests',
                        data: requests,
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.3
                    }, {
                        label: 'Errors',
                        data: errors,
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.3
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            position: 'bottom',
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        function updateEndpointChart() {
            const ctx = document.getElementById('endpointChart').getContext('2d');
            
            // Aggregate endpoint data
            const endpoints = {};
            Object.values(statsData.allTime || {}).forEach(ipData => {
                Object.entries(ipData.endpoints || {}).forEach(([endpoint, count]) => {
                    endpoints[endpoint] = (endpoints[endpoint] || 0) + count;
                });
            });
            
            const sortedEndpoints = Object.entries(endpoints)
                .sort(([, a], [, b]) => b - a)
                .slice(0, 8);
            
            if (endpointChart) {
                endpointChart.destroy();
            }
            
            endpointChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: sortedEndpoints.map(([endpoint]) => endpoint),
                    datasets: [{
                        data: sortedEndpoints.map(([, count]) => count),
                        backgroundColor: [
                            '#667eea',
                            '#764ba2',
                            '#f59e0b',
                            '#10b981',
                            '#ef4444',
                            '#8b5cf6',
                            '#ec4899',
                            '#14b8a6'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            position: 'bottom',
                        }
                    }
                }
            });
        }

        function updateErrorsTable() {
            const tbody = document.getElementById('errorsTableBody');
            const errors = [];
            
            Object.values(statsData.allTime || {}).forEach(ipData => {
                (ipData.errors || []).forEach(error => errors.push(error));
            });
            
            const recentErrors = errors
                .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
                .slice(0, 10);
            
            if (recentErrors.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #999;">No errors recorded</td></tr>';
                return;
            }
            
            tbody.innerHTML = recentErrors.map(error => {
                const date = new Date(error.timestamp);
                const statusClass = 'status-' + Math.floor(error.statusCode / 100) * 100;
                return \`
                    <tr>
                        <td>\${date.toLocaleString('en-US', { 
                            month: 'short', 
                            day: 'numeric', 
                            hour: '2-digit', 
                            minute: '2-digit',
                            second: '2-digit'
                        })}</td>
                        <td><code>\${error.endpoint}</code></td>
                        <td>\${error.error}</td>
                        <td><span class="error-status \${statusClass}">\${error.statusCode}</span></td>
                    </tr>
                \`;
            }).join('');
        }

        function refreshStats() {
            loadStats();
        }

        async function exportStats(format) {
            try {
                if (format === 'json') {
                    const blob = new Blob([JSON.stringify(statsData, null, 2)], { type: 'application/json' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'proxy-stats-' + new Date().toISOString().split('T')[0] + '.json';
                    a.click();
                    URL.revokeObjectURL(url);
                } else if (format === 'csv') {
                    let csv = 'IP,Total Requests,Successful,Failed,Success Rate,Avg Duration (ms)\\n';
                    Object.entries(statsData.allTime || {}).forEach(([ip, data]) => {
                        const successRate = data.totalRequests > 0 
                            ? ((data.successfulRequests / data.totalRequests) * 100).toFixed(2)
                            : '0.00';
                        const avgDuration = data.totalRequests > 0
                            ? (data.totalDuration / data.totalRequests).toFixed(2)
                            : '0.00';
                        csv += \`\${ip},\${data.totalRequests},\${data.successfulRequests},\${data.failedRequests},\${successRate},\${avgDuration}\\n\`;
                    });
                    
                    const blob = new Blob([csv], { type: 'text/csv' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'proxy-stats-' + new Date().toISOString().split('T')[0] + '.csv';
                    a.click();
                    URL.revokeObjectURL(url);
                }
            } catch (error) {
                console.error('Export error:', error);
                alert('Failed to export stats');
            }
        }

        // Load stats on page load
        loadStats();
        
        // Auto refresh every 30 seconds
        setInterval(loadStats, 30000);
    </script>
</body>
</html>
  `.trim();
}